package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.utils.HttpUtil;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.BaseException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //1.远程调用微信凭证校验接口获取openid
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(url, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = (String) jsonObject.get("openid");
        if(openid==null){
            throw new BaseException("微信登录失败");
        }

        //2.根据openid查询用户数据
        User user = userMapper.getByOpenid(openid);

        if(user!=null) {
            //2.1 用户数据不为null，直接返回
            return user;
        }
        //2.2 用户数据为null，注册用户（将openid插入user表中）
        user = new User();
        user.setOpenid(openid);
        user.setCreateTime(LocalDateTime.now());
        userMapper.insert(user); //不仅要插入数据，并且里面要获取到自增长主键值

        //3.返回登录的用户对象
        return user;
    }


}
